﻿package org.grizzly.web.interceptor;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.common.PubMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;


public class BaseInterceptor extends AbstractInterceptor {

	
	private static final long serialVersionUID = -2185920708747626659L;
	
	private static final Log logger = LogFactory.getLog(BaseInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext ac = invocation.getInvocationContext();
		Object action = invocation.getAction();
		
		ServletContext servletContext = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);
		WebApplicationContext wc = WebApplicationContextUtils.getWebApplicationContext(servletContext);

		HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
		String userRemoteAddr = request.getRemoteAddr();
		
		String actionName = ac.getName();
		//String methodName = ((BaseAction)action).getMethod();
		String methodName = "";
		
		Map map = ac.getParameters();
		
		String[] _methodName = (String[]) map.get("method");
		if (methodName != null) {
			methodName = _methodName[0];
		}
		StringBuffer info = new StringBuffer("");
		info.append("\r\n------------------START REQUEST------------------\r\n");
		//info.append("Interceptor BaseInterceptor ... ");
		info.append("Request from: [" + userRemoteAddr + "]\r\n");
		info.append("Request time: [" + PubMethod.getDateTime() + "]\r\n");
		info.append("Action: [" + actionName + "]\r\n");
		info.append("Method: [" + methodName + "]\r\n");
		logger.info(info.toString());
		
		return invocation.invoke();
	}

}
